package models;

import java.util.*;

import javax.persistence.*;

import play.db.jpa.*;

/**
 * 
 * @author Islam Al-aareg
 * @version 1.0
 * 
 */
@Entity
public class Tag extends Model {
	public String name;
	@ManyToMany
	public List<ActionItem> relatedActionItems;
	@ManyToMany
	public List<Topic> relatedTopics;
	@ManyToMany
	public List<User> subscribers;
	@ManyToMany
	public List<Idea> relatedIdeas;

	/**
	 * 
	 * @param name
	 *            the name of the tag
	 */

	public Tag(String name) {
		this.name = name;
		this.relatedActionItems = new ArrayList<ActionItem>();
		this.relatedTopics = new ArrayList<Topic>();
		this.subscribers = new ArrayList<User>();
		this.relatedIdeas = new ArrayList<Idea>();

	}
	
	/**
	 * method to add new action item to the list of related action items
	 * 
	 * @param itemId
	 * 			id of the item to be added to this tag
	 * 
	 * @return the method return the Tag instance after the modifications
	 */
	
	public Tag addActionItem(long itemId) {
		ActionItem item = ActionItem.findById(itemId);
		if(item != null) {
			this.relatedActionItems.add(item);
			this.save();
			return this;
		}
		
		return null;
	}

	/**
	 * 
	 * @return list of all tags
	 */
	public static List<Tag> getListOfAllTags() {
		return Tag.findAll();
	}
	
	/**
	 * @author Ahmed Mahmoud
	 * @return
	 */
	public boolean cascadeDelete(){
		for(ActionItem item : relatedActionItems){
			item.tags.remove(this);
			item.save();
		}
		for(Topic topic : relatedTopics){
			topic.tags.remove(this);
			topic.save();
		}
		for(User user: subscribers){
			user.subscribedTags.remove(this);
			user.save();
		}
		for(Idea idea : relatedIdeas){
			idea.tags.remove(this);
			idea.save();
		}
		
		this.delete();
		
		return true;
	}

}